package model

import (
	"errors"
	"gopkg.in/mgo.v2/bson"
	"src/config"
	newtime "src/util/time"
)

type Tipoff struct {
	Id         bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"`
	Status     int           `bson:"status" json:"status"`
	User_id    string        `bson:"user_id" json:"user_id"`
	Context_id string        `bson:"context_id" json:"context_id"`
	Issue_time int64         `bson:"issue_time" json:"issue_time"`
	Text       string        `bson:"text" json:"text"`
	Level      int           `json:"level"`
}

func CreateTipoff(a Tipoff) (Tipoff, error) {
	query := bson.M{
		"_id": bson.ObjectIdHex(a.Context_id),
	}
	switch a.Level {
	case 0:
		_, err := findForumPost(query, DefaultSelector)
		if err != nil {
			return Tipoff{}, err
		}
		break
	case 1:
		_, err := findComment(query, DefaultSelector)
		if err != nil {
			return Tipoff{}, err
		}
		break
	default:
		return Tipoff{}, errors.New("error level")
	}
	a.Issue_time = newtime.GetMilliTimestamp()
	a.Status = config.ApplicationNewStatus
	err := insertApplication(a)
	return a, err

}

func GetTipoff() ([]Application, error) {
	query := bson.M{
		"status": config.ApplicationNewStatus,
	}
	return findApplicationsALL(query)
}

func ReadTipoff(id string) error {
	query := bson.M{
		"_id": bson.ObjectIdHex(id),
	}
	update := bson.M{
		"$set": bson.M{
			"status": config.ApplicationReadStatus,
		},
	}
	return updateApplication(query, update)

}

/*********************************************************************/
func updateTipoff(query, update interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	ApplicationTable := sess.DB(DBNAME).C(TIPOFFTABLE)

	return ApplicationTable.Update(query, update)
}
func insertTipoff(docs ...interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	ForumPostTable := sess.DB(DBNAME).C(TIPOFFTABLE)

	return ForumPostTable.Insert(docs...)
}
func findTipoff(query, selector interface{}) (Tipoff, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	ApplicationTable := sess.DB(DBNAME).C(TIPOFFTABLE)

	Tipoff := Tipoff{}
	err := ApplicationTable.Find(query).Select(selector).One(&Tipoff)
	return Tipoff, err
}

func findTipoffs(query, selector interface{}, page, perPage int, fields ...string) ([]Tipoff, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	ApplicationTable := sess.DB(DBNAME).C(TIPOFFTABLE)

	Tipoff := []Tipoff{}
	err := ApplicationTable.Find(query).Select(selector).Sort(fields...).Skip((page - 1) * perPage).Limit(perPage).All(&Tipoff)
	return Tipoff, err
}
func findTipoffsALL(query interface{}) ([]Tipoff, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	ApplicationTable := sess.DB(DBNAME).C(TIPOFFTABLE)

	Tipoff := []Tipoff{}
	err := ApplicationTable.Find(query).All(&Tipoff)
	return Tipoff, err
}
